<template>
  <el-upload
    class="upload-demo"
    :action="uploadActionUrl"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    :before-upload="beforeAvatarUpload"
    :on-success="handleAvatarSuccess"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件，且不超过500kb
    </div>
  </el-upload>
</template>
<script>
import { GetImage, DeleteImage } from "../api/files";
export default {
  data() {
    return {
      //图片数组
      fileList: [],
      //传入图片的id
      imgeId: "",
      dialogFormAvatarFullUrl: "",
    };
  },
  methods: {
    //删除指定id图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
      console.log(file.id);

      //删除api调用
      DeleteImage(file.id).then((data) => {
        console.log(data);
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
    //点击图片
    handlePreview(file) {
      console.log(file);
    },
    // 图片上传前的钩子函数，用于检测上传文件的大小、类型等
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式！");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB！");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      this.imgeId = URL.createObjectURL(file.raw);
      // 保存相对路径
      let prePath = res.data[0];
      // 显示使用完整路径
      let fullPath = URL.createObjectURL(file.raw);
      this.imgeId = prePath;
      this.dialogFormAvatarFullUrl = fullPath;
      //打印图片Id
      console.log(this.imgeId);
      //添加成功提示
      this.$message({
        type: "success",
        message: "添加成功!",
      });
    },
    //拉取图表全部数据
    fetchData(){
      GetImage()
      .then((data) => {
        var res = data.data;
        console.log(res);
        for (var index = 0; index < res.length; index++) {
          var obj = {
            id: res[index].id,
            name: "id：" + res[index].id + "name：" + res[index].originName,
            url: "http://localhost:5000/files/" + res[index].id,
          };
          this.fileList.push(obj);
        }
        
      })
      .catch((err) => {
        console.log(err);
      });
    }
  },
  mounted() {
    this.fetchData()
    
  },
  //图片上传的api地址
  computed: {
    uploadActionUrl() {
      const baseUrl = "http://localhost:5000/";
      const uploadUrl = "files/uploadfiles";
      return baseUrl + uploadUrl;
    },
  },
};
</script>